package com.swu.cx.alwayslearning

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

import android.widget.Button
import android.widget.TextView
import com.swu.cx.alwayslearning.classloader.Student
import com.swu.cx.alwayslearning.myretrofit.MyRetrofit
import com.swu.cx.alwayslearning.myretrofit.MyWeatherApi
import com.swu.cx.alwayslearning.util.FileUtil
import okhttp3.*
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val myRetrofit = MyRetrofit.Builder()
            .baseUrl("https://api.seniverse.com")
            .build()
        val api = myRetrofit.create(MyWeatherApi::class.java)
        findViewById<Button>(R.id.button).setOnClickListener {
            get(api)
        }
        findViewById<Button>(R.id.button2).setOnClickListener {
            post(api)
        }
    }

    fun get(api: MyWeatherApi) {

        val call = api.getWeather("北京")
        call.enqueue(object : okhttp3.Callback{
            override fun onFailure(call: Call, e: IOException) {

            }

            override fun onResponse(call: Call, response: Response) {
                val str = response.body()?.string()
                runOnUiThread {
                    findViewById<TextView>(R.id.textView).text = str
                }
            }

        })
    }

    fun post(api: MyWeatherApi) {
        val call = api.postWeather("北京")
        call.enqueue(object : okhttp3.Callback{
            override fun onFailure(call: Call, e: IOException) {

            }

            override fun onResponse(call: Call, response: Response) {
                val str = response.body()?.string()
                runOnUiThread {
                    findViewById<TextView>(R.id.textView).text = str
                }
            }

        })
    }



}